﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;

namespace Service
{
    public class CaptchaHelper
    {
        /// <summary>生成指定长度的随机验证码（字母+数字）</summary>
        public static string GenerateCaptchaCode(int length = 4)
        {
            const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            Random rnd = new Random();
            return new string(Enumerable.Repeat(chars, length)
                .Select(s => s[rnd.Next(s.Length)]).ToArray());
        }

        /// <summary>根据验证码生成图片字节数组</summary>
        public static byte[] GenerateCaptchaImage(string captchaCode, int width = 120, int height = 40)
        {
            using (Bitmap bitmap = new Bitmap(width, height))
            using (Graphics g = Graphics.FromImage(bitmap))
            {
                // 1. 绘制背景
                g.Clear(Color.White);

                // 2. 绘制干扰线（示例：3条随机干扰线）
                Random rnd = new Random();
                for (int i = 0; i < 3; i++)
                {
                    int x1 = rnd.Next(width);
                    int y1 = rnd.Next(height);
                    int x2 = rnd.Next(width);
                    int y2 = rnd.Next(height);
                    g.DrawLine(new Pen(Color.LightGray, 1), x1, y1, x2, y2);
                }

                // 3. 绘制验证码文字
                Font font = new Font("Arial", 20, FontStyle.Bold | FontStyle.Italic);
                g.DrawString(captchaCode, font, Brushes.Blue, 10, 5);

                // 4. 转为字节数组返回
                using (MemoryStream ms = new MemoryStream())
                {
                    bitmap.Save(ms, ImageFormat.Png);
                    return ms.ToArray();
                }
            }
        }
    }
}